﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

using System.Configuration;

using Ivy.Common.Framework.GeneralUtility;
using Ivy.UserRegistration.Entity;
using Ivy.UserRegistration.IBusinessLogic;
using Ivy.UserRegistration.BusinessLogic;

using DasIdeen.ViewEntity;

namespace DasIdeen.UserControls
{
    public partial class RegistrationControl : System.Web.UI.UserControl
    {
        #region  Variable & constant
        //All constants and local variable should be declared here
        AntiSpamUtility antiSpam = new AntiSpamUtility();
        const string constCultureInfo = "CultureInfo";
        #endregion  Variable & constant

        #region Constructor & Destructor
        //Generally not needed in UI layer
        #endregion Constructor & Destructor

        #region Properties
        //UI layer may have public custom properties. these are very handy for User Controls
        #endregion Properties

        #region Public Methods
        //UI layer may have public custom properties. these are very handy for User Controls
        #endregion Public Methods

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            try //All events in pages or user control should have try{} catch {} block.
            {
                //First check if the current logged in user is having proper role/authorization to access this page or not.
                if (IsUserAutherization())
                {
                    //TODO - Your code to display the initial layout/data etc.
                    if (!IsPostBack)
                    {
                        InitializeScreen();
                    }
                }
                else
                {
                    //TODO - Your code to redirect page to "NOT AUTHORIZED" page or any other page as required by the business logic.
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void btnAvailibity_Click(object sender, EventArgs e)
        {
            try
            {
                IUserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
                if (string.IsNullOrEmpty(txtLoginId.Text.Trim()))
                {
                    lblAvailibity.ForeColor = System.Drawing.Color.Red;
                    lblAvailibity.Text = "is empty";
                }
                else
                {
                    if (lUserRegistrationBus.IsLoginIDExisting(txtLoginId.Text.Trim()))
                    {
                        lblAvailibity.ForeColor = System.Drawing.Color.Red;
                        lblAvailibity.Text = "Not Available";
                    }
                    else
                    {
                        lblAvailibity.ForeColor = System.Drawing.Color.Green;
                        lblAvailibity.Text = "Available";
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {

                if (this.txtAntiSpam.Text.Trim() == hidCorrectAnswer.Value)
                {
                    //true
                    UserContext tempUserSession;
                    User lUser;
                    UserProfile lUserProfile;
                    UserProfileImage lUserProfileImage;
                    IUserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
                    if (this.btnRegister.Text != "Update")
                    {
                        //Insert new user logic
                        lUser = new User();
                        TranslateUIControlsToUserEntity(lUser);
                        if (lUserRegistrationBus.RegisterNewUser(lUser))
                        {
                            lUser = lUserRegistrationBus.GetUserByLoginID(lUser.UserLoginID); //this is needed to get the latest creation date and reset entity state.
                            lUserProfileImage = new UserProfileImage();
                            lUserProfileImage.UserKey = lUser.UserKey;

                            lUserProfile = new UserProfile();
                            lUserProfile.UserKey = lUser.UserKey;
                            lUserProfile.UserFullName = lUser.UserFirstName + " " + lUser.UserLastName;
                            lUserProfile.Sys_CreatedByID = lUser.UserKey.ToString();

                            TranslateUIControlsToUserProfileEntity(lUserProfile);
                            if (lUserRegistrationBus.SaveUserProfile(lUserProfile))
                            {
                                lUserProfileImage = new UserProfileImage();
                                TranslateUIControlsToUserProfileImageEntity(lUserProfileImage, lUser.UserKey);
                                if (lUserRegistrationBus.SaveUserProfileImage(lUserProfileImage))
                                {
                                    lUserRegistrationBus.SendVerificationCodeEmail(lUser);
                                    if (Session["UserContext"] != null)
                                    {
                                        tempUserSession = (UserContext)Session["UserContext"];
                                        if (tempUserSession.CurrentUser == null)
                                        {
                                            tempUserSession.CurrentUser = lUser;
                                        }
                                    }
                                    else
                                    {
                                        tempUserSession = new UserContext();
                                        tempUserSession.UserIPAddress = GetUserIPAddress();
                                        tempUserSession.UserBrowser = HttpContext.Current.Request.Browser.Browser;
                                        tempUserSession.CurrentUser = lUser;
                                    }
                                    Session["UserContext"] = tempUserSession;
                                    Response.Redirect("~/Pages/UserVerification.aspx");
                                }
                            }
                            
                        }
                        else
                        {
                            lblAvailibity.ForeColor = System.Drawing.Color.Red;
                            lblAvailibity.Text = "Not Available";
                        }
                        
                    }
                    else
                    {
                        // update logic;
                        if (Session["UserContext"] != null)
                        {
                            tempUserSession = (UserContext)Session["UserContext"];
                            if (tempUserSession.CurrentUser != null)
                            {
                                lUser = tempUserSession.CurrentUser;
                                TranslateUIControlsToUserEntity(lUser);
                                if (lUserRegistrationBus.UpdateRegisteredUser(lUser))
                                {
                                    tempUserSession.CurrentUser = lUser;
                                    Session["UserContext"] = tempUserSession;

                                    lUserProfile = lUserRegistrationBus.GetUserProfileByID(lUser.UserKey.ToString());
                                    if (lUserProfile == null)
                                    {
                                        lUserProfile = new UserProfile();
                                        lUserProfile.Sys_CreatedByID = lUser.UserKey.ToString();
                                    }
                                    lUserProfile.UserKey = lUser.UserKey;
                                    lUserProfile.UserFullName = lUser.UserFirstName + " " + lUser.UserLastName;
                                    //lUserProfile.Sys_CreatedByID = lUser.UserKey.ToString();

                                    TranslateUIControlsToUserProfileEntity(lUserProfile);
                                    if (lUserRegistrationBus.SaveUserProfile(lUserProfile))
                                    {
                                        lUserProfileImage = new UserProfileImage();
                                        TranslateUIControlsToUserProfileImageEntity(lUserProfileImage, lUser.UserKey);
                                        if (lUserRegistrationBus.SaveUserProfileImage(lUserProfileImage))
                                        {
                                            //Refresh user context with latest data
                                            Response.Redirect("~/Default.aspx");
                                        }
                                        else
                                        {
                                            //to show message that update is un-sussessful
                                        }
                                    }
                                    else
                                    {
                                        //to show message that update is un-sussessful
                                    }
                                }
                                else
                                {
                                    //to show message that update is un-sussessful
                                }
                            }
                            else
                            {
                                //Session available, but may be user is not logged in.
                                //Unlikely in current suituation because user profile can be update only by the logged in user
                            }
                        }
                        else
                        {
                            //No session, may be user is not logged in.
                            //Unlikely in current suituation because user profile can be update only by the logged in user
                        }
                    }
                }

                else
                {
                    hidCorrectAnswer.Value = antiSpam.GenerateMathFormula();
                    lblAntiSpam.Text = antiSpam.MathFormula;
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
                //Need to display the exception message to the user or log it in application log.
            }
            ClearScreen();
        }

        #endregion Events

        #region Private Methods

        /// <summary>
        /// This method is to check if the current logged in user is having proper role/authorization to access this page or not.
        /// </summary>
        private bool IsUserAutherization()
        {
            bool _IsUserAutherization = false;
            //TODO - Your code to check authorization goes here.

            //for the time being let us allow the user to access this page.
            //but remove the below line once you have a proper logic.
            _IsUserAutherization = true;

            return _IsUserAutherization;
        }

        /// <summary>
        /// This method is to clear all UI controls which are data binded.
        /// </summary>
        private void ClearScreen()
        {
        }

        /// <summary>
        /// This method is to bind all the UI control like dropdown list or list box etc with the required initial data, 
        /// </summary>
        private void FillLoadLookUpData()
        {
        }

        private void FillScreenWithCurrentUserData(string pUserLoginID, string pUserKey)
        {
            User lUser = new User();
            UserProfile lUserProfile;
            UserProfileImage lUserProfileImage;
            IUserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
            lUser = lUserRegistrationBus.GetUserByLoginID(pUserLoginID);
            lUserProfile = lUserRegistrationBus.GetUserProfileByID(pUserKey);
            lUserProfileImage = lUserRegistrationBus.GetUserProfileImageByUserKey(Convert.ToInt32(pUserKey));
            UserContext tempUserSession;
            if (Session["UserContext"] != null)
            {
                tempUserSession = (UserContext)Session["UserContext"];
                if (tempUserSession.CurrentUser.UserKey == lUser.UserKey)
                {
                    tempUserSession.CurrentUser = lUser;
                    TranslateEntityToUIControls(lUser, lUserProfile, lUserProfileImage);
                }
                else
                {
                    //Session available, but may be user is not logged in.
                    //Unlikely in current suituation because user profile can be update only by the logged in user
                }
            }
            else
            {
                //No session, may be user is not logged in.
                //Unlikely in current suituation because user profile can be update only by the logged in user
            }
        }

        /// <summary>
        /// This method is to load the UI with initial set of data based of the business logic.
        /// </summary>
        private void InitializeScreen()
        {
            ClearScreen();
            FillLoadLookUpData();
            if (Session["UserContext"] != null)
            {
                UserContext tempUserSession = (UserContext)Session["UserContext"];
                if (tempUserSession.CurrentUser != null)
                {
                    this.lblPageHeader.Text = "Edit My Profile";
                    this.btnRegister.Text = "Update";
                    this.txtLoginId.Enabled = false;
                    this.tdPassword.Visible = false;
                    this.tdConfirmPassword.Visible = false;

                    this.btnAvailibity.Visible = false;

                    FillScreenWithCurrentUserData(tempUserSession.CurrentUser.UserLoginID, tempUserSession.CurrentUser.UserKey.ToString());
                }
                else
                {
                    this.lblPageHeader.Text = "New Registration";
                    this.btnRegister.Text = "Register";
                    this.txtLoginId.Enabled = true;
                    this.txtPassword.Enabled = true;
                    this.txtConfirmPassword.Enabled = true;

                    this.btnAvailibity.Visible = true;
                    ClearScreen();
                }
            }
            else
            {
                this.lblPageHeader.Text = "New Registration";
                this.btnRegister.Text = "Register";
                this.txtLoginId.Enabled = true;
                this.txtPassword.Enabled = true;
                this.txtConfirmPassword.Enabled = true;

                this.btnAvailibity.Visible = true;
                ClearScreen();
            }
            if (!IsPostBack)
            {
                hidCorrectAnswer.Value = antiSpam.GenerateMathFormula();
                lblAntiSpam.Text = antiSpam.MathFormula;
            }
        }

        /// <summary>
        /// This method is to copy the entity properties that need to be displayed in the UI controls to the UI control.
        /// Example - [pUser] is an instance of an entity and is filled with specific USER data.
        /// and this user instance is to be displayed is an UI control text boxes.
        /// A sample code will look like the following:
        ///  this.txtFirstName.Text = pUser.UserFirstName; 
        ///  this.txtLastName.Text  = pUser.UserLastName; 
        ///  this.txtLoginId.Text   = pUser.UserLoginID;
        /// </summary>
        private void TranslateEntityToUIControls(User pUser, UserProfile pUserProfile, UserProfileImage pUserProfileImage)
        {
            try
            {
                this.txtFirstName.Text = pUser.UserFirstName;
                this.txtLastName.Text = pUser.UserLastName;
                this.txtLoginId.Text = pUser.UserLoginID;

                this.txtPassword.Enabled = true;
                this.txtConfirmPassword.Enabled = true;

                this.txtPassword.TextMode = TextBoxMode.SingleLine;
                this.txtConfirmPassword.TextMode = TextBoxMode.SingleLine;
                this.txtPassword.Text = StringUtility.DecryptString(pUser.UserPassword);

                this.txtConfirmPassword.Text = this.txtPassword.Text;

                this.txtPassword.Enabled = false;
                this.txtConfirmPassword.Enabled = false;
                this.txtEmailId.Text = pUser.UserPrimaryEmailID;
                if (pUserProfile != null)
                {
                    this.txtAlternateEmailId.Text = pUserProfile.UserAlternateEmailID;
                    this.ddlGender.Text = pUserProfile.UserSex;
                    if (pUserProfile.UserDateOfBirth != null)
                    {
                        this.txtDOB.Text = pUserProfile.UserDateOfBirth.Value.ToShortDateString();
                    }
                    this.txtContactNo.Text = pUserProfile.UserContactNumber;
                    this.txtAddress.Text = pUserProfile.UserContactAddress;
                }
                if (pUserProfileImage != null)
                {
                    if (pUserProfileImage.UserImageData != null && pUserProfileImage.UserImageType != string.Empty)
                    {
                        this.UserProfileImg.ImageUrl = "data:" + pUserProfileImage.UserImageType + ";base64," + Convert.ToBase64String(pUserProfileImage.UserImageData);
                    }
                    else
                    {
                        //Display default image
                        this.UserProfileImg.ImageUrl = "";
                    }
                }
                else
                {
                    //Display default image
                    this.UserProfileImg.ImageUrl = "";
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
                //Need to display the exception message to the user or log it in application log.
            }
        }

        /// <summary>
        /// This method is to copy the user entered data from the UI controls to the entity instance that will be used to sent the entity to any other layer.
        /// Example - [pUser] is an instance of an entity and is to be filled with specific USER data that has been captured in the screen.
        /// A sample code will look like the following:
        ///  pUser.UserFirstName = this.txtFirstName.Text; 
        ///  pUser.UserLastName  = this.txtLastName.Text; 
        ///  pUser.UserLoginID   = this.txtLoginId.Text; 
        /// </summary>
        private void TranslateUIControlsToUserEntity(User pUser)
        {
            pUser.UserLoginID = this.txtLoginId.Text;
            if (this.lblPageHeader.Text != "Edit My Profile")
            {
                pUser.UserPassword = StringUtility.EncryptString(this.txtPassword.Text);
            }
            else
            {
                UserContext tempUserSession = (UserContext)Session["UserContext"];
                if (tempUserSession.CurrentUser != null)
                {
                    pUser.UserPassword = tempUserSession.CurrentUser.UserPassword;
                }
            }
            pUser.UserFirstName = this.txtFirstName.Text;
            pUser.UserLastName = this.txtLastName.Text;
            pUser.UserPrimaryEmailID = this.txtEmailId.Text;
            pUser.UserVerificationCode = StringUtility.GenerateRandomString(6);
            pUser.Sys_CreatedByID = "-1";
        }

        private void TranslateUIControlsToUserProfileEntity(UserProfile pUserProfile)
        {

            if (this.ddlGender.Text.Substring(0, 1) == "M" || this.ddlGender.Text.Substring(0, 1) == "F")
            {
                pUserProfile.UserSex = this.ddlGender.Text.Substring(0, 1);
            }
            pUserProfile.UserAlternateEmailID = this.txtAlternateEmailId.Text;


            AppSettingsReader _AppSettingsReader = new AppSettingsReader();
            string _CultureInfo = _AppSettingsReader.GetValue(constCultureInfo, typeof(string)).ToString();

            IFormatProvider _CultureFormatProvider = new System.Globalization.CultureInfo(_CultureInfo, true);
            if (!string.IsNullOrEmpty(txtDOB.Text.Trim()))
            {
                pUserProfile.UserDateOfBirth = DateTime.Parse(txtDOB.Text.Trim(), _CultureFormatProvider, System.Globalization.DateTimeStyles.AssumeLocal);
            }
            else
            {
                pUserProfile.UserDateOfBirth = null;
            }
            pUserProfile.UserContactNumber = this.txtContactNo.Text;
            pUserProfile.UserContactAddress = this.txtAddress.Text;

        }

        private void TranslateUIControlsToUserProfileImageEntity(UserProfileImage pUserProfileImage, int pUserKey)
        {
            //string ImageName = string.Empty;
            byte[] lImageData = null;
            if (this.ImgUpload.PostedFile != null && this.ImgUpload.PostedFile.FileName != "")
            {
                //ImageName = Path.GetFileName(this.ImgUpload.FileName);
                lImageData = new byte[this.ImgUpload.PostedFile.ContentLength];
                HttpPostedFile UploadedImage = this.ImgUpload.PostedFile;
                UploadedImage.InputStream.Read(lImageData, 0, (int)this.ImgUpload.PostedFile.ContentLength);
                this.UserProfileImg.ImageUrl = "data:" + this.ImgUpload.PostedFile.ContentType + ";base64," + Convert.ToBase64String(lImageData);
                pUserProfileImage.UserKey = pUserKey;
                // Why this is hard coded?
                //pUserProfileImage.UserLoginID = "SystemSuperAdmin";
                pUserProfileImage.UserLoginID = this.txtLoginId.Text; ;
                pUserProfileImage.UserImageData = lImageData;
                pUserProfileImage.UserImageType = this.ImgUpload.PostedFile.ContentType;
                pUserProfileImage.UserImageFileName = this.ImgUpload.PostedFile.FileName;
                if (pUserKey < 1)
                {
                    pUserKey = -1;
                }
                pUserProfileImage.Sys_CreatedByID = pUserKey.ToString();
            }
            else
            {
                
            }
            
        }

        private string GetUserIPAddress()
        {
            //The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a 
            //client connecting to a web server through an HTTP proxy or load balancer
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Current.Request.UserHostAddress;
                if (string.IsNullOrEmpty(ip))
                {
                    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
            }
            return ip;
        }

        //private void UploadUserProfileImage()
        //{
            
        //    UserProfileImage lUserProfileImage = new UserProfileImage();
        //    UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
        //    if (this.ImgUpload.PostedFile != null && this.ImgUpload.PostedFile.FileName != "")
        //    {
        //        ImageName = Path.GetFileName(this.ImgUpload.FileName);
        //        ImageData = new byte[this.ImgUpload.PostedFile.ContentLength];
        //        HttpPostedFile UploadedImage = this.ImgUpload.PostedFile;
        //        UploadedImage.InputStream.Read(ImageData, 0, (int)this.ImgUpload.PostedFile.ContentLength);

        //        TranslateUIControlsToUserProfileImageEntity(lUserProfileImage, ImageData, this.ImgUpload.PostedFile.FileName, this.ImgUpload.PostedFile.ContentType);
        //        this.UserProfileImg.ImageUrl = "data:" + this.ImgUpload.PostedFile.ContentType + ";base64," + Convert.ToBase64String(ImageData);
        //        lUserRegistrationBus.RegisterNewUserProfileImage(lUserProfileImage);
        //    }
        //}
        #endregion Private Methods

    }
}